package controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import model.JoinTeamMsg;
import model.Race;
import model.RaceMsg;
import model.Team;
import service.CompanyService;
import service.RaceService;
import service.TeamService;
import service.UserService;
import service.impl.CompanyServiceImpl;
import service.impl.RaceServiceImpl;
import service.impl.TeamServiceImpl;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 燕子豪
 * @Date: 2023/1/2 20:38
 */
@WebServlet("/teamByRaceAndName")
public class TeamByRaceAndNameServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        TeamService teamServiceImpl = new TeamServiceImpl();
        RaceService raceServiceImpl = new RaceServiceImpl();
        UserService userServiceImpl = new UserServiceImpl();
        //将前端的参数转为json
        BufferedReader reader = new BufferedReader(request.getReader());
        StringBuilder json = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            json.append(line);
        }
        JSONObject jsonObject = JSON.parseObject(json.toString());

        List<JoinTeamMsg> teamMsgList = new ArrayList<>();
        //解析前端的参数：pageIndex，pageSize暂指定为5
        int pageSize = 5;
        int rid = Integer.parseInt(jsonObject.getString("rid"));
        String tname = jsonObject.getString("tname");
        int pageIndex = Integer.parseInt(jsonObject.getString("pageIndex"));

        //创建List容器
        List<Team> teamList = teamServiceImpl.teamByRaceAndName(rid, tname, pageIndex, pageSize);
        for (Team team : teamList) {
            JoinTeamMsg joinTeamMsg = new JoinTeamMsg();
            joinTeamMsg.setTeam(team);
            joinTeamMsg.setRace(raceServiceImpl.getRaceById(rid));
            joinTeamMsg.setLeader(userServiceImpl.findById((int) team.getLid()));
            joinTeamMsg.setTeamUserCount(teamServiceImpl.getTeamUserCount(((int)team.getTid())));

            teamMsgList.add(joinTeamMsg);
        }


        int count = teamServiceImpl.teamByRaceAndNameCount(rid,tname);

        //将数据List打包为json发给前端
        JSONObject message = new JSONObject();
        message.put("teamMsg", teamMsgList);
        message.put("pageCount", count % pageSize != 0 ? count / pageSize + 1 : count / pageSize);
        response.getWriter().write(message.toString());
    }
}